package bb.lanxing.mvp.model;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import android.text.TextUtils;

import bb.lanxing.activity.deeplink.DeepLinkPathConstants;
import bb.lanxing.common.config.Constants;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.RouteBookPoint;
import bb.lanxing.model.json.Route;
import bb.lanxing.nav.BaiduNavConvert;
import bb.lanxing.nav.PolyAnalyzer;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetOnSubscribe;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.RouteBookUtil;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class SprintNavModelImpl {
    public Observable<Route> getRoute(final RouteBook routeBook, final int i) {
        String uuid = routeBook.getUuid();
        if (routeBook.getSourceType() == 0) {
            uuid = uuid + ".bb";
        } else if (routeBook.getSourceType() == 3) {
            uuid = uuid + ".bd";
        }
        if (new File(AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION) + uuid).exists()) {
            return Observable.just(routeBook.getUuid()).subscribeOn(Schedulers.computation())
                    .flatMap(new Func1<String, Observable<Route>>() {
                        @Override
                        public Observable<Route> call(String str) {
                            try {
                                return Observable.just(SprintNavModelImpl.this.parseRoute(str));
                            } catch (IOException | JSONException e) {
                                return Observable.error(e);
                            }
                        }
                    });
        }
        String fileName = routeBook.getFileName();
        if (!TextUtils.isEmpty(fileName) && fileName.endsWith(DeepLinkPathConstants.FILE_SUFFIX_GPX)) {
            return Observable.just(fileName).subscribeOn(Schedulers.computation())
                    .flatMap(new Func1<String, Observable<Route>>() {
                        @Override
                        public Observable<Route> call(String str) {
                            List<RouteBookPoint> byLushuId = RouteBookPoint.getByLushuId(routeBook.getId());
                            if (byLushuId == null || byLushuId.isEmpty()) {
                                return Observable.error(new IllegalStateException("No lushu point found !"));
                            }
                            ArrayList arrayList = new ArrayList(byLushuId.size());
                            for (RouteBookPoint lushuPoint : byLushuId) {
                                arrayList.add(lushuPoint.getLatLng());
                            }
                            return Observable.just(new PolyAnalyzer().analyse(arrayList, i));
                        }
                    });
        }
        return Observable.create(new NetOnSubscribe.Builder(
                MyHttpClient.downloadRouteBook(routeBook.getServerType(), routeBook.getServerId()))
                .append("lushu", routeBook).build()).subscribeOn(Schedulers.io()).flatMap(response -> {
                    RouteBook routeBook2 = (RouteBook) response.getParam("lushu");
                    try {
                        String bodyString = response.getBodyString();
                        String httpUrl = response.getRequest().url().toString();
                        if (!httpUrl.toLowerCase().endsWith(DeepLinkPathConstants.FILE_SUFFIX_GPX)
                                && !httpUrl.toLowerCase().endsWith(".gpxtest")) {
                            if (!httpUrl.toLowerCase().endsWith(".json")
                                    && !httpUrl.toLowerCase().endsWith(".jsontest")) {
                                RouteBookUtil.parseGpxFile(bodyString, routeBook2);
                                return Observable.just(SprintNavModelImpl.this.parseRoute(routeBook2.getUuid()));
                            }
                            RouteBookUtil.parseDirection(bodyString, null, routeBook2, routeBook2.getSourceType());
                            return Observable.just(SprintNavModelImpl.this.parseRoute(routeBook2.getUuid()));
                        }
                        RouteBookUtil.parseGpxFile(bodyString, routeBook2);
                        return Observable.just(SprintNavModelImpl.this.parseRoute(routeBook2.getUuid()));
                    } catch (IOException | JSONException e) {
                        e.printStackTrace();
                        return Observable.error(e);
                    }
                });
    }

    public Route parseRoute(String str) throws JSONException, IOException {
        File file = new File(AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION) + (str + ".bb"));
        if (file.exists()) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bArr = new byte[4096];
            while (true) {
                int read = fileInputStream.read(bArr);
                if (read == -1) {
                    break;
                }
                byteArrayOutputStream.write(bArr, 0, read);
            }
            byteArrayOutputStream.flush();
            String decryptGZIP = AppFileUtils.decryptGZIP(byteArrayOutputStream.toByteArray());
            byteArrayOutputStream.close();
            fileInputStream.close();
            List parseArray = JSONObject.parseArray(JSON.parseObject(decryptGZIP).getString("routes"), Route.class);
            if (parseArray != null && !parseArray.isEmpty()) {
                return (Route) parseArray.get(0);
            }
            return null;
        }
        File file2 = new File(AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION) + (str + ".bd"));
        if (!file2.exists()) {
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream2 = new ByteArrayOutputStream();
        FileInputStream fileInputStream2 = new FileInputStream(file2);
        byte[] bArr2 = new byte[4096];
        while (true) {
            int read2 = fileInputStream2.read(bArr2);
            if (read2 != -1) {
                byteArrayOutputStream2.write(bArr2, 0, read2);
            } else {
                byteArrayOutputStream2.flush();
                String decryptGZIP2 = AppFileUtils.decryptGZIP(byteArrayOutputStream2.toByteArray());
                byteArrayOutputStream2.close();
                fileInputStream2.close();
                return BaiduNavConvert.parseRoute(new org.json.JSONObject(decryptGZIP2));
            }
        }
    }
}
